package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by sc on 2017/8/20.
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService {
    Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String upload(MultipartFile file, String path) {
        String filename = file.getOriginalFilename();
        String fileExtensionName = filename.substring(filename.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;

        logger.info("开始上传文件,文件名{},路径{},新文件名{}");
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetfile = new File(path, uploadFileName);
        try {
            file.transferTo(targetfile);
            //todo  上传到ftp  删除upload文件下的文件
            FTPUtil.uploadFile(Lists.<File>newArrayList(targetfile));

            targetfile.delete();
        } catch (IOException e) {
            logger.error("上传异常" + e);
            return null;
        }
        return targetfile.getName();
    }
}
